<?php
/**
 * User: Hufeng
 * Date: 2017/6/12 11:35
 * Desc: REDIS
 */
namespace App\Common\Util;
use Predis\Client;
use SasPHP\Config;

class Redis{
    public $client;
    public function __construct(){
        $confObj = new Config(BASEDIR.'/App/Common/Conf');
        $conf = $confObj->offsetGet('config');
        $config = $conf['REDIS'];

        $redisSentinels = $config['REDISSENTINELS'];
        $redisOptions = $config['REDISOPTIONS'];
        $this->client = new Client($redisSentinels,$redisOptions);
    }

    public function __destruct(){
        $this->client->quit();
    }

    /*单次获得锁资格*/
    public function getLock($key){
        if($this->client->setnx($key,1)){
            return true;
        }else{
            return false;
        }
    }
    /*循环获得锁资格,直至获取到*/
    public function getLockEnabel($key){
        if($this->client->setnx($key,1)){
            return true;
        }else{
            $this->getLockEnabel($key);
        }
        return true;
    }
    /*释放锁*/
    public function removeLock($key){
        $this->client->del([$key]);
    }
}
